package io.mft.commons.function.response;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.mft.commons.exception.MFTException;
import io.mft.commons.function.response.kv.KVMap;
import io.mft.commons.function.response.kv.KVMapList;
import io.mft.commons.function.response.kv.PageObject;
import io.mft.commons.function.response.kv.PageObject.PageMetadata;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class DefaultResponseStorage implements ResponseWriter, ResponseReader {

	protected Map<String, DsName> dsName = new HashMap<>();
	protected Map<String, List<?>> dataMap = new HashMap<String, List<?>>();
	protected Map<String, PageMetadata> pageMap = new HashMap<String, PageMetadata>();
	protected String mainDsKey=DsName.DEFAULT_RESULT_KEY;
	@Override

	public void write(String key, DsType type, KVMapList value) {
		write(key, type, DsValueType.kv, value);
	}

	
	private <T> void write(String key, DsType type,DsValueType valueType, List<T> value) {
		DsName t = new DsName();
		t.setName(key);
		t.setType(type);
		t.setValueType(valueType);
		dsName.put(key, t);
		dataMap.put(key, value);
	}
	
	private <T> void writeObject(String key,DsValueType valueType, PageObject<T> pager) {
		pageMap.put(key, pager.pageMetadata());
		write(key, DsType.page, valueType,pager.getList());
	}
	public void clear() {
		dsName.clear();
		dataMap.clear();
		pageMap.clear();
	}

	@Override
	public void clear(String key) {
		dsName.remove(key);
		dataMap.remove(key);
		pageMap.remove(key);
		
	}
	@Override
	public void write(String key, PageObject<KVMap> pager) {
		writeObject(key, pager);
	}

	@Override
	public KVMapList list(String key) {
		List<KVMap> list=listObject(key);
		if (list!=null) {
			KVMapList kvMapList=new KVMapList(list);
			return kvMapList;
		}else {
			return null;
		}
	}

	@Override
	public List<DsName> dsNames() {
		List<DsName> list = new ArrayList<>(dsName.values());
		return list;
	}

	@Override
	public PageMetadata pageMetadata(String key) {
		return pageMap.get(key);
	}

	@Override
	public DsName getDsName(String key) {
		return dsName.get(key);
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> List<T> listObject(String key) {
		try {
			List<?> v= dataMap.get(key);
			if (v==null) {
				return null;
			}
			List<T> list=new ArrayList<>();
			v.forEach(kv->{
				T t=(T)kv;
				list.add(t);
			});
			return list;
		} catch (Throwable e) {
			log.error("",e);
			throw new MFTException(-1, "响应数据读取异常");
		}

	}

	@Override
	public <T> void writeObject(String key, PageObject<T> pager) {
		writeObject(key, DsValueType.object, pager);
	}


	@Override
	public <T> void writeObject(String key, DsType type, List<T> value) {
		write(key, type, DsValueType.object, value);
	}


	@Override
	public String mainDsKey() {
		return mainDsKey;
	}


	@Override
	public void mainDsKey(String mainDsKey) {
		this.mainDsKey=mainDsKey;
	}
}
